package character.sprite.gui;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

import javax.swing.JPanel;

import character.sprite.model.CharacterSprite;
import data.ObjectDatabase;

public class CharacterSpriteAnimator extends JPanel {

	private static final long serialVersionUID = 3978215870106376766L;

	public static final int SPRITE_WIDTH = 24;
	public static final int SPRITE_HEIGHT = 32;

	private static final int FRAME_DELAY = 200;
	private static final Color BG_COLOR = new Color(150, 150, 255);

	private String charSpriteClassName, spriteGUID;

	private int currentFrame;
	private boolean animationDone;
	private BufferedImage buffer;

	public CharacterSpriteAnimator(int width, int height, String spriteGUID) {
		this.setSize(width, height);

		charSpriteClassName = CharacterSprite.class.getCanonicalName();

		this.spriteGUID = spriteGUID;
		this.animationDone = false;
		this.buffer = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_ARGB);
		this.setBackground(BG_COLOR);

		new Thread(new Runnable() {
			@Override
			public void run() {
				while (!animationDone) {
					drawSprite();
					try {
						Thread.sleep(FRAME_DELAY);
					} catch (InterruptedException e) {
					}
				}
			}
		}).start();
	}

	private void drawSprite() {
		Graphics2D g2d = (Graphics2D) buffer.getGraphics();
		if (g2d != null) {
			g2d.setColor(BG_COLOR);
			g2d.fillRect(0, 0, buffer.getWidth(), buffer.getHeight());
			g2d.scale(2.0f, 2.0f);
			for (int i = 0; i < 4; i++) {
				if (this.spriteGUID != null) {
					CharacterSprite sprite = (CharacterSprite) ObjectDatabase
							.getInstance().getEditorObject(
									this.charSpriteClassName, this.spriteGUID);
					g2d.drawImage(sprite.getFullImage().getSubimage(
							currentFrame * SPRITE_WIDTH, i * SPRITE_HEIGHT,
							SPRITE_WIDTH, SPRITE_HEIGHT), i
							* ((buffer.getWidth() - (SPRITE_WIDTH * 3)) / 5),
							(buffer.getHeight() / 4) - (SPRITE_HEIGHT / 2),
							null);
				}
			}
			currentFrame++;
			if (currentFrame > 2) {
				currentFrame = 0;
			}
		}
		g2d = (Graphics2D) this.getGraphics();
		if (g2d != null) {
			g2d.drawImage(buffer, 0, 0, null);
		}
	}

	public void stopAnimation() {
		this.animationDone = true;
	}

}
